package com.zhl.model.token.service.impl;

import com.zhl.common.config.GobleException;
import com.zhl.common.constant.CacheConstant;
import com.zhl.common.constant.ResponseCode;
import com.zhl.common.vo.Result;
import com.zhl.common.vo.ServerResponse;
import com.zhl.model.token.service.TokenService;
import com.zhl.util.RandomUtil;
import com.zhl.util.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.text.StrBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

@Service
public class TokenServiceImpl implements TokenService {

    private static final String TOKEN_NAME = "token";

    @Autowired
    private RedisUtil redisUtil;

//    @Override
//    public ServerResponse createToken() {
//        String str = RandomUtil.UUID32();
//        StrBuilder token = new StrBuilder();
//        token.append(CacheConstant.TOKEN_PREFIX).append(str);
//
//        redisUtil.set(token.toString(), token.toString(), CacheConstant.EXPIRE_TIME_MINUTE);
//
//        return ServerResponse.success(token.toString());
//    }

    @Override
    public Result createToken() {
        String str = RandomUtil.UUID32();
        StrBuilder token = new StrBuilder();
        token.append(CacheConstant.TOKEN_PREFIX).append(str);
        HashMap hashMap = new HashMap();
        hashMap.put("token",token.toString());
        redisUtil.set(token.toString(), token.toString(), CacheConstant.EXPIRE_TIME_MINUTE);
        return Result.ok(hashMap);
    }

    @Override
    public void checkToken(HttpServletRequest request) {
        String token = request.getHeader(TOKEN_NAME);
        if (StringUtils.isBlank(token)) {// header中不存在token
            token = request.getParameter(TOKEN_NAME);
            if (StringUtils.isBlank(token)) {// parameter中也不存在token
                throw new GobleException(ResponseCode.ILLEGAL_ARGUMENT.getMsg());
            }
        }

        if (!redisUtil.hasKey(token)) {
            throw new GobleException(ResponseCode.REPETITIVE_OPERATION.getMsg());
        }

        Long del = redisUtil.del(token);
        if (del <= 0) {
            throw new GobleException(ResponseCode.REPETITIVE_OPERATION.getMsg());
        }
    }

}
